<?php
namespace app\common\service\Users;

use think\facade\Request;
use think\facade\Cache;
use think\Db;

use app\common\entity\User;
use app\admin\model\Config;

class Payment
{
    protected $code_id = 102345;
    protected $code_key = 'xEUIyG7KZ37i0fYC5h4TM2UEbxErSfR2';

    protected $domain = 'http://www.4owk.cn';

    public function creat_order($user,$price,$type = 1)
    {
        if (!$user) {
            $this->error = '用户信息错误';
            return false;
        }
        if ($price <= 0) {
            $this->error = '订单金额有误';
            return false;
        }
        if (!in_array($type,[1,2,3])) {
            $this->error = '支付方式有误';
            return false;
        }

        $data = [
            'id' => $this->code_id,
            'key' => $this->code_key,
            'type' => $type,
            'price' => $price,
            'pay_id' => $this->build_order_no('fmi'),
            'notify_url' => $this->domain.'/index/Callback/payment',
            'return_url' => $this->domain.'/index/Member/index',
            'outTime' => 86400,
        ];

        ksort($data); //重新排序$data数组
        reset($data); //内部指针指向数组中的第一个元素

        $sign = ''; //初始化需要签名的字符为空
        $urls = ''; //初始化URL参数为空

        foreach ($data AS $key => $val) { //遍历需要传递的参数
            if ($val == ''||$key == 'sign') continue; //跳过这些不参数签名
            if ($sign != '') { //后面追加&拼接URL
                $sign .= "&";
                $urls .= "&";
            }
            $sign .= "$key=$val"; //拼接为url参数形式
            $urls .= "$key=" . urlencode($val); //拼接为url参数形式并URL编码参数值

        }
        $query = $urls . '&sign=' . md5($sign .$this->code_key); //创建订单所需的参数
        $url = "http://api2.fateqq.com:52888/creat_order/?{$query}"; //支付页面
        
        // 生成本地订单
        $order = [
            'user_id' => $user->id,
            'type' => $type,
            'price' => $price,
            'pay_id' => $data['pay_id'],
            'status' => 0,
            'endTime' => time() + 86400,
            'create_time' => time()
        ];
        $result = Db::name('user_payment')->insert($order);
        if (!$result){
            $this->error = '创建本地订单失败';
            return false;
        }

        return $url;
    }

    public function doCallback($post = [])
    {
        if (!$post) return false;
        ksort($post); //排序post参数
        reset($post); //内部指针指向数组中的第一个元素

        $sign = '';//初始化
        foreach ($post AS $key => $val) { //遍历POST参数
            if ($val == '' || $key == 'sign') continue; //跳过这些不签名
            if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
            $sign .= "$key=$val"; //拼接为url参数形式
        }
        if (!$post['pay_no'] || md5($sign . $this->code_key) != $post['sign']) { //不合法的数据
            exit('fail');  //返回失败 继续补单
        } else { //合法的数据
            //业务处理
            $order = Db::name('user_payment')->where("pay_id",$post['pay_id'])->find();
            if (!$order) return false;
            if ($order['status'] != 0) return false;

            Db::startTrans();

            $new_data = [];
            $new_data['status'] = 1;
            $new_data['pay_no'] = $post['pay_no']; //流水号
            $new_data['pay_time'] = $post['pay_time'];
            $new_data['finish_time'] = time();

            $result = Db::name('user_payment')->where("pay_id", $post['pay_id'])->update($new_data);
            if (!$result) {
                Db::rollback();
                return false;
            }

            $obj_user = new \app\common\entity\User();
            $user = $obj_user->get($order['user_id']);
            if (!$user) return false;

            $service = new \app\common\service\Users\Service();
            $result = $service->adjustVoucher($user,$order['price'],$order['price'],0,1,'充值认筹券');
            if (!$result) {
                Db::rollback();
                return false;
            }

            $voucher_switch = Config::getValue('voucher_switch');
            if ($voucher_switch == 1) { // 充值奖励
                $result = $service->rechargeReward($user,$order['price']);
                if (!$result) {
                    Db::rollback();
                    return false;
                }
            }

            Db::commit();

            exit('success'); //返回成功
        }
    }

    /**
     * 生成订单号
     */
    private function build_order_no($suffix = 'o') {
        return $suffix.date('md').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}